package com.itqf.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * projectName: store_parent
 *
 * @author: 赵伟风
 * time: 2021/6/7 17:33
 * description:字符串数组转化器.针对dts_admin账号的角色属性dts_ids属性
 */
//指定生成java数据类型
@MappedTypes(Integer[].class)
//对应的数据库类型
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler extends BaseTypeHandler<Integer[]> {

    private ObjectMapper mapper =new ObjectMapper();

    /**
     * 插入数据的时候!整数数组要切换成字符串,保存到数据库中!
     * @param preparedStatement
     * @param i  占位符的位置
     * @param ids 插入的数据
     * @param jdbcType jdbc数据库类型
     * @throws SQLException
     */
    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Integer[] ids, JdbcType jdbcType) throws SQLException {

        String idsstr = mapper.writeValueAsString(ids);
        //插入数据的时候,对应位置,数组转成字符串!
        preparedStatement.setObject(i, idsstr);
    }

    /**
     * 数据库根据列名取值
     * @param resultSet
     * @param columnName
     * @return
     * @throws SQLException
     */
    @SneakyThrows
    @Override
    public Integer[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {

        //获取值 '[1,2]'
        String idsStr = resultSet.getString(columnName);

        Integer[] integers = mapper.readValue(idsStr, Integer[].class);

        return integers;
    }

    @SneakyThrows
    @Override
    public Integer[] getNullableResult(ResultSet resultSet, int index) throws SQLException {

        //获取值 '[1,2]'
        String idsStr = resultSet.getString(index);

        Integer[] integers = mapper.readValue(idsStr, Integer[].class);

        return integers;
    }

    @SneakyThrows
    @Override
    public Integer[] getNullableResult(CallableStatement callableStatement, int index) throws SQLException {
        //获取值 '[1,2]'
        String idsStr = callableStatement.getString(index);

        Integer[] integers = mapper.readValue(idsStr, Integer[].class);

        return integers;
    }
}
